#!/usr/bin/lua -f
-- note the limitation of line mode
s=arg[0] while strsub(s,-1)~="/" do s=strsub(s,1,-2) end dofile(s.."common.lua")
opt,narg,myst=getopts({b=1,C=1,l=1,filesonly=1})
if myst then opt.l=myst end
if arg[narg] then
	if arg[narg]~="-" then readfrom(arg[narg]) end
	if arg[narg+1] then prefix=narg else prefix="x" end
end
if not opt.l and not opt.b and not opt.C then opt.l=1000 end
if not opt.C then opt.C=1E99 else opt.C=bkm(opt.C) end
if not opt.b and not opt.l then opt.l=1E99 end
if opt.b then opt.b=bkm(opt.b) end
if opt.l then opt.l=bkm(opt.l) end
if arg[narg+1] then prefix=narg else prefix="x" end
a="a" b="a" c=""
while 1 do
	oname=prefix..c..a..b
	if opt.b then
		remain=opt.b
		while remain>0 do
			B=read(min(remain,8192))
			if not B then break end
			if not hdl then
				hdl=openfile(oname,"wb")
			end
			remain=remain-strlen(B)
			write(hdl,B)
		end
	else
		lines=0 bytes=0
		if opt.C then remain=opt.C end
		while 1 do
			if LB then B=LB LB=nil else B=read() end
			if not B then break end
			if not hdl then
				hdl=openfile(oname,"wb")
			end
			LAST=B
			B=B.."\n"
			if bytes+strlen(B)>opt.C then LB=B break end
			write(hdl,B)
			lines=lines+1
			bytes=bytes+strlen(B)
			if lines==opt.l then lines=0 bytes=0 break end
		end
	end
	if hdl then
		closefile(hdl)
		hdl=nil
	end
	if not B then exit(0) end
	if b=="z" then a=strchar(strbyte(a)+1) b="a"
		if a=="z" then
			a="a"
			if c=="" then
				prefix="xz"
				c="a"
			else
				c=strchar(strbyte(c)+1)
			end
		end
	else
		b=strchar(strbyte(b)+1)
	end
end
